﻿using System;
using System.Security.Cryptography;

namespace MSL.Utility.Security
{
    /// <summary>
    /// MD5加密类
    /// </summary>
    public class MD5Encrypt
    {
        /// <summary>
        /// MD5 加密，byte[]型
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static byte[] MD5(byte[] data)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            return md5.ComputeHash(data);
        }

        /// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="text">字符串</param>
        /// <returns></returns>
        public static string MD5(string text)
        {
            return MD5(text, 32);
        }

        /// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="text">字符串</param>
        /// <param name="code">加密方式,16或32</param>
        /// <returns></returns>
        public static string MD5(string text, int code)
        {
            if (code == 16) //16位MD5加密（取32位加密的9~25字符） 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5").ToUpper().Substring(8, 16);
            }
            else//32位加密 
            {
                return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "MD5").ToUpper();
            }
        }

        /// <summary>
        /// MD5 加密，byte[]型加密为string
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string MD5ToHex(byte[] data)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            string t = "";
            string tTemp = "";
            for (int i = 0; i < result.Length; i++)
            {
                tTemp = System.Convert.ToString(result[i], 16);
                if (tTemp.Length != 2)
                {
                    switch (tTemp.Length)
                    {
                        case 0: tTemp = "00"; break;
                        case 1: tTemp = "0" + tTemp; break;
                        default: tTemp = tTemp.Substring(0, 2); break;
                    }
                }
                t += tTemp;
            }
            return t;
        }

        /// <summary>
        /// 加密实现
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string MD5ToHex(string text)
        {
            byte[] data = System.Text.ASCIIEncoding.Unicode.GetBytes(text);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);
            string t = "";
            for (int i = 0; i < result.Length; i++)
            {
                t += System.Convert.ToString(result[i], 16);
            }
            return t;
        }

    }
}
